<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="110px">
      <el-form-item label="脚本名称" prop="name">
        <el-input
          style="width:295px;"
          v-model="queryParams.name"
          placeholder="脚本名称,支持模糊查询"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="最近执行人" prop="name">
        <el-input
          style="width:295px;"
          v-model="queryParams.lastExecUserName"
          placeholder="最近执行人,支持模糊查询"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" style="display: flex; align-items: center;">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['hawk-eye:repair:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['hawk-eye:repair:remove']"
        >删除
        </el-button>
      </el-col>
      <div style="margin-left: auto;">
        <el-link
          style="font-size: 13px; color: blue;"
          :underline="false"
          @click="handleDoc">
          什么是修复脚本？
        </el-link>
      </div>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="repairList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="脚本名称" align="center" prop="name" :show-overflow-tooltip="true">
        <template #default="scope">
          <el-tooltip v-if="scope.row.repairDesc" :content="scope.row.repairDesc" placement="top">
                <span style="color: #1890ff; cursor: pointer;">
                  {{ scope.row.name }}
                </span>
          </el-tooltip>
          <span v-else>{{scope.row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column label="最近执行时间" align="center" prop="lastExecTime"/>
      <el-table-column label="最近执行状态" align="center" prop="lastExecSuccessful">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.lastExecSuccessful === 1" type="success" effect="plain">成功</el-tag>
          <el-tag v-else-if="scope.row.lastExecSuccessful === 0" type="danger" effect="plain">失败</el-tag>
          <el-tag v-else type="info" effect="plain">未执行</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="最近执行人" align="center" prop="lastExecUserName"/>
      <el-table-column label="成功次数/执行总次数" align="center" prop="execCount">
        <template slot-scope="scope">
          <span>{{`${scope.row.execSuccessCount ? scope.row.execSuccessCount : 0}/${scope.row.execCount ? scope.row.execCount : 0}`}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="ssubmittedmall-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['hawk-eye:repair:edit']"
          >编辑
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-caret-right"
            @click="handleExecuteRepairApi(scope.row)"
            v-hasPermi="['hawk-eye:repair:edit']"
          >执行
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-order"
            @click="handleRepairLog(scope.row)"
            v-hasPermi="['hawk-eye:repair:list']"
          >日志
          </el-button>
          <el-button
            size="mini"
            type="text"
            style="color: red;"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['hawk-eye:repair:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="Number(total)>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="title" :visible.sync="open" width="1180px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="18">
            <el-form-item label="关联缺陷" prop="problemText">
              <el-input v-model="form.problemText" placeholder="该脚本能够修复的缺陷,非必选项" clearable
                        @focus="handleSelectAlarmLog"
                        :disabled="false">
                <template slot="append">
                  <el-button @click="handleSelectAlarmLog" icon="el-icon-search"></el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="脚本名称" prop="name">
              <el-input v-model="form.name" placeholder="建议规范命名,方便维护管理" maxlength="30" show-word-limit/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="功能描述" prop="repairDesc">
              <el-input v-model="form.repairDesc" placeholder="请简要说明脚本作用、目的" type="textarea" maxlength="200"
                        :rows="2"
                        show-word-limit/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="请求方式" prop="reqType">
              <el-select
                v-model="form.reqType"
                placeholder="GET/POST"
              >
                <el-option
                  v-for="item in reqTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="请求地址" prop="reqUri">
              <el-input v-model="form.reqUri" placeholder="请求地址格式:http://www.xxx.xx/xxx/xx?id=&name=xxx 动态参数不声明参数值即可,如:id=">
                <el-button slot="append" icon="el-icon-document-copy" v-clipboard="form.reqUri"
                           v-clipboard:success="copySuccessHandle"
                           v-clipboard:error="copyErrorHandle"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="请求头" prop="reqHeadersArray">
            <el-button @click="addHeader" style="margin-bottom: 15px" type="primary" size="mini">新增
            </el-button>
            <el-button @click="addHeader(1)" style="margin-bottom: 15px" type="primary" size="mini">
              Authorization
            </el-button>
            <el-table :data="form.reqHeadersArray" style="width:100%;" height="200" border>
              <el-table-column prop="name" label="名称">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.name" clearable autocomplete="off" size="small" placeholder="请输入请求头属性名"
                            maxlength="50" show-word-limit/>

                </template>
              </el-table-column>
              <el-table-column prop="value" label="数值">
                <template slot-scope="scope">
                  <el-select v-if="scope.row.isAuthorization === 1" v-model="scope.row.type" style="width: 120px">
                    <el-option
                      v-for="item in authHeaderOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                  <el-input v-if="scope.row.isAuthorization === 1" v-model="scope.row.value"
                            style="width: 310px; flex: 2;" autocomplete="off" clearable size="small"
                            placeholder="如果不填写,则为动态数据"/>
                  <el-input v-if="scope.row.isAuthorization !== 1" v-model="scope.row.value"
                            style="flex: 2;" autocomplete="off" clearable size="small" placeholder="如果不填写,则为动态数据"/>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template slot-scope="scope">
                  <el-button size="mini" type="danger" plain style="color: red;"
                             @click="removeHeader(scope.$index, scope.row)">删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="请求体" prop="reqBody">
              <code-editor v-model="form.reqBody"
                           style="line-height: 1;"
                           :auto-format="true"
                           :smart-indent="true"
                           theme="dracula"
                           :indent-unit="2"
                           :line-wrap="false"
                           ref="codeEditor">
              </code-editor>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <problem-record-table ref="problemRecordTable" @submitted="handleSelectedProblem"/>
    <repair-log-table ref="repairLogTable"/>
    <repair-params-table ref="repairParamsTable"/>
  </div>
</template>

<script>
  import {
    repairApiList,
    repairApiDetail,
    addRepairApi,
    updateRepairApi,
    removeRepairApi
  } from "@/api/hawkeye/repair";
  import ProblemRecordTable from "./modules/ProblemRecordTable";
  import RepairLogTable from "./modules/RepairLogTable";
  import RepairParamsTable from "./modules/RepairParamsTable";
  import {CodeEditor} from "bin-code-editor"

  export default {
    name: "RepairApi",
    components: {ProblemRecordTable, RepairLogTable, RepairParamsTable, CodeEditor},
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 【请填写功能名称】表格数据
        repairList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10
        },
        // 表单参数
        form: {
          reqHeadersArray: [],
          reqBody: `{}`,
          problemList: []
        },
        reqTypeOptions: [
          {
            label: "GET",
            value: 1
          }, {
            label: "POST",
            value: 2
          }
        ],
        authHeaderOptions: [
          {
            label: "Bearer",
            value: "Bearer"
          }, {
            label: "Basic",
            value: "Basic"
          }
        ],
        // 表单校验
        rules: {
          name: [
            {required: true, message: "脚本名称不能为空", trigger: "blur"}
          ],
          reqUri: [
            {required: true, message: "请求地址不能为空", trigger: "blur"}
          ],
          reqType: [
            {required: true, message: "请求方式不能为空", trigger: "blur"}
          ],
          reqBody: [
            {
              validator: function (rule, value, callback) {
                try {
                  if (!value) {
                    callback()
                  }
                  JSON.parse(value);
                  callback()
                } catch (error) {
                  callback(new Error("请输入正确的JSON格式"))
                }
              },
              trigger: "blur"
            }
          ]
        }
      };
    },
    created() {
      let repairApiName = this.$route.query.repairApiName;
      if (repairApiName) {
        this.$set(this.queryParams, 'name', repairApiName)
      }
      this.getList();
    },
    computed: {
      problemText: () => {
        return (rows) => {
          if (!rows || rows.length === 0) {
            return "";
          }
          return rows.length > 1 ? `${rows[0].problemName}等${rows.length}个缺陷` : rows[0].problemName;
        }
      }
    },
    methods: {
      /** 查询【请填写功能名称】列表 */
      getList() {
        this.loading = true;
        repairApiList(this.queryParams).then(res => {
          this.repairList = res.records || [];
          this.total = res.total;
        }).finally(() => {
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          problemText: null,
          reqType: null,
          reqParams: null,
          reqHeadersArray: [],
          reqBody: `{}`,
          name: null,
          reqUri: null,
          lastExecUserName: null,
          lastExecTime: null,
          lastExecResult: null,
          execCount: null,
          execSuccessCount: null,
          createUserName: null,
          createTime: null,
          problemList: []
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      handleSelectAlarmLog() {
        this.$refs.problemRecordTable.open(this.form.id, false);
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.showRepairExecInfoPane = false;
        this.open = true;
        this.title = "添加";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.showRepairExecInfoPane = true;
        const id = row.id || this.ids
        repairApiDetail(id).then(res => {
          let data = res.data;
          if (data.reqHeaders) {
            data.reqHeadersArray = JSON.parse(data.reqHeaders);
          } else {
            data.reqHeadersArray = [];
          }
          this.form = data;
          this.$set(this.form, 'problemText', this.problemText(data.problemList));
          this.open = true;
          this.title = "编辑";
        });
      },
      handleRepairLog(row) {
        this.$refs.repairLogTable.openTable(row.id);
      },
      handleExecuteRepairApi(row) {
        this.$modal.confirm('确认执行该修复脚本吗？').then(() => {
          this.$refs.repairParamsTable.open(row.id, row.reqType, false, null);
        })
      },
      // 复制成功回调函数
      copySuccessHandle(value) {
        this.$modal.msgSuccess("内容已复制到剪切板,可进行粘贴");
      },
      // 复制失败回调函数
      copyErrorHandle(value) {
        this.$modal.msgError("复制失败,请确认浏览器支持复制功能");
      },
      addHeader(auth) {
        let header = {
          name: '',
          value: ''
        }
        if (auth === 1) {
          header['isAuthorization'] = auth
          header['name'] = 'Authorization'
          header['type'] = 'Bearer'
        }
        this.form.reqHeadersArray.push(header);
      },
      removeHeader(index, row) {
        this.form.reqHeadersArray.splice(index, 1);
      },
      /** 提交按钮 */
      submitForm() {
        if (!this.form.reqBody) {
          this.form.reqBody = "{}";
        }
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.reqHeadersArray) {
              this.form.reqHeaders = JSON.stringify(this.form.reqHeadersArray);
            }
            if (this.form.id != null) {
              updateRepairApi(this.form).then(res => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addRepairApi(this.form).then(res => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除数据？').then(function () {
          return removeRepairApi(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      },
      handleSelectedProblem(rows) {
        this.$set(this.form, 'problemText', this.problemText(rows))
        this.$set(this.form, 'problemList', rows || [])
      },
      handleDoc() {
        let url = 'https://www.wolai.com/bsKRMZWE8dM6iqq8Wy3BxS';
        if (!url) {
          return;
        }
        window.open(url);
      }
    }
  };
</script>
<style scoped="css">
  .el-dialog__body::v-deep {
    padding: 1px 20px;
  }
</style>
